import { useCallback, useEffect, useState } from "react"
import {
  createTask,
  deleteTask,
  editTask,
  fetchTasks,
  startTask,
  stopTask,
} from "../services/api"
import type { Task } from "../types/task"

export function useTasks(query: string) {
  const [tasks, setTasks] = useState<Task[]>([])
  const [loading, setLoading] = useState(true)

  const loadTasks = useCallback(async () => {
    setLoading(true)
    try {
      const data: Task[] = await fetchTasks()
      setTasks(
        data.filter(
          (task) =>
            task.name.includes(query) ||
            (task.description && task.description.includes(query))
        )
      )
    } catch (error) {
      // 错误处理可在页面层做
    } finally {
      setLoading(false)
    }
  }, [query])

  useEffect(() => {
    loadTasks()
    const interval = setInterval(loadTasks, 5000)
    return () => clearInterval(interval)
  }, [loadTasks])

  const handleCreate = async (payload: {
    name: string
    template: string
    description?: string
  }) => {
    await createTask({
      name: payload.name,
      template: payload.template ?? "",
    })
    await loadTasks()
  }
  const handleEdit = async (
    id: string,
    payload: { name: string; template: string; description?: string }
  ) => {
    await editTask(id, {
      name: payload.name,
      description: payload.description ?? "",
    })
    await loadTasks()
  }
  const handleDelete = async (id: string) => {
    await deleteTask(id)
    await loadTasks()
  }
  const handleStart = async (id: string) => {
    await startTask(id)
    await loadTasks()
  }
  const handleStop = async (id: string) => {
    await stopTask(id)
    await loadTasks()
  }

  return {
    tasks,
    loading,
    loadTasks,
    handleCreate,
    handleEdit,
    handleDelete,
    handleStart,
    handleStop,
    setTasks,
  }
}
